package com.wyp168.leetcode.listnode;

/**
 * @ClassName MergeInBetweenSolution
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2023/1/30 18:27
 */
public class MergeInBetweenSolution {
    public static void main(String[] args) {
        MergeInBetweenSolution mergeInBetweenSolution = new MergeInBetweenSolution();
        ListNode a0 = new ListNode(0);
        ListNode a1 = new ListNode(1);
        ListNode a2 = new ListNode(2);
        ListNode a3 = new ListNode(3);
        ListNode a4 = new ListNode(4);
        ListNode a5 = new ListNode(5);
        ListNode a6  = new ListNode(6);

        ListNode aListNode = mergeInBetweenSolution.designListNode(a0, a1, a2, a3, a4, a5, a6);


        ListNode b0 = new ListNode(1000000);
        ListNode b1 = new ListNode(1000001);
        ListNode b2 = new ListNode(1000002);
        ListNode b3 = new ListNode(1000003);
        ListNode b4 = new ListNode(1000004);

        ListNode bListNode = mergeInBetweenSolution.designListNode(b0, b1, b2, b3, b4);

        ListNode listNode = mergeInBetweenSolution.mergeInBetween(aListNode, 2, 5, bListNode);
        System.out.println(listNode.toString());
    }

    /**
     * 删除list1链表中下表从 a 到 b 的元素，并拼接上链表list2
     *
     * @param list1
     * @param a
     * @param b
     * @param list2
     * @return
     */
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode[] nodes = findNode(list1, a, b);
        ListNode nodeStart = nodes[0];
        ListNode nodeEnd = nodes[1];
        nodeStart.next = list2;
        ListNode tempListNode = list2;
        while (tempListNode.next != null) {
            tempListNode = tempListNode.next;
        }

        tempListNode.next = nodeEnd;
        return list1;
    }

    /**
     * 根据下标获取链表对应下标节点信息
     *
     * @param listNode
     * @param indexA
     * @param indexB
     * @return
     */
    public ListNode[] findNode(ListNode listNode, int indexA, int indexB) {
        if (indexA < 0) {
            throw new ArrayIndexOutOfBoundsException("下标index越界");
        }
        if (indexB < indexA) {
            throw new RuntimeException("参数不合法");
        }

        ListNode[] nodes = new ListNode[2];

        for (int i = 0; i < indexB; i ++) {
            if (indexA == i + 1) {
                nodes[0] = listNode;
            }
            listNode = listNode.next;
        }

        nodes[1] = listNode.next;

        return nodes;
    }

    public ListNode designListNode(ListNode... nodes) {
        for (int i = 0; i < nodes.length - 1; i++) {
            nodes[i].next = nodes[i + 1];
        }
        return nodes[0];
    }
}
